import { PaymentChannel } from '@prisma/client';
import { TopPayService, createTopPayService, isTopPayConfigured, CreateOrderRequest as TopPayCreateOrderRequest, CreatePayoutOrderRequest as TopPayCreatePayoutOrderRequest } from './topPayService';
import { Pay668Service, createPay668Service, isPay668Configured, CreatePay668OrderRequest, CreatePay668PayoutRequest, Pay668PayoutResponse } from './pay668Service';
import { LspPayService, createLspPayService, isLspPayConfigured, CreateLspPayOrderRequest, CreateLspPayPayoutRequest, LspPayOrderResponse, LspPayPayoutResponse } from './lspPayService';
import { HuifengPayService, createHuifengPayService, isHuifengConfigured, CreateHuifengOrderRequest, CreateHuifengPayoutRequest, HuifengOrderResponse, HuifengPayoutResponse } from './huifengPayService';
import { NaskiPayService, createNaskiPayService, isNaskiConfigured, CreateNaskiOrderRequest, NaskiOrderResponse } from './naskiPayService';
import { Logger, AppError, ErrorCode } from '../utils/logger';
import { channelConfigService } from './channelConfigService';
import { ChannelSelectionResult } from '../types/channelConfig';

// 统一的创建订单请求参数
export interface CreatePaymentOrderRequest {
  userId: number;
  amount: number;
  paymentChannel: PaymentChannel;
  paymentMethod: 'BankTransfer' | 'qrPay';
  orderId: string;
  transAccNo: string; // 银行卡号（必填）
  paymentName: string; // 付款人真实名称（必填）
  bankCode: string; // 银行编码（必填）
  customerEmail?: string; // 客户邮箱（可选）
  customerPhone?: string; // 客户手机号（可选）
  extendParam?: string; // 透传参数
}

// 统一的创建提现订单请求参数
export interface CreatePayoutOrderRequest {
  amount: number;
  paymentChannel: PaymentChannel;
  paymentMethod: 'BankTransfer' | 'qrPay';
  orderId: string;
  receiverName: string; // 收款人姓名（必填）
  receiverBankCard: string; // 收款银行卡号（必填）
  bankCode: string; // 银行编码（必填）
  accountName?: string; // 账户名称
  bankName?: string; // 银行名称
  certificate?: string; // 证件号
  subbranch?: string; // 支行名称
  customerEmail?: string; // 客户邮箱（可选）
  customerPhone?: string; // 客户手机号（可选）
  userIp?: string; // 用户IP（可选）
  extra?: string; // 扩展字段（JSON字符串）
  remark?: string; // 支付备注（可选）
}

// 统一的支付响应
export interface PaymentResponse {
  success: boolean;
  platOrderNum?: string;
  payUrl?: string;
  qrCodeUrl?: string;
  errorCode?: string;
  errorMessage?: string;
  rawResponse: any; // 原始响应数据
}

// 统一的异步通知数据
export interface PaymentNotification {
  channel: PaymentChannel;
  orderId: string;
  platOrderNum: string;
  status: string;
  amount: string;
  payFee?: string;
  rawData: any;
}

export class PaymentService {
  private topPayService: TopPayService;
  private pay668Service: Pay668Service;
  private lspPayService: LspPayService;
  private huifengPayService: HuifengPayService;
  private naskiPayService: NaskiPayService;

  constructor() {
    this.topPayService = createTopPayService();
    this.pay668Service = createPay668Service();
    this.lspPayService = createLspPayService();
    this.huifengPayService = createHuifengPayService();
    this.naskiPayService = createNaskiPayService();
  }

  /**
   * 检查支付渠道是否已配置
   */
  isChannelConfigured(channel: PaymentChannel): boolean {
    switch (channel) {
      case PaymentChannel.TOPPAY:
        return isTopPayConfigured();
      case PaymentChannel.PAY668:
        return isPay668Configured();
      case PaymentChannel.LSPPAY:
        return isLspPayConfigured();
      case PaymentChannel.HUIFENG:
        return isHuifengConfigured();
      case PaymentChannel.NASKI:
        return isNaskiConfigured();
      default:
        return false;
    }
  }

  /**
   * 获取可用的支付渠道
   */
  getAvailableChannels(): PaymentChannel[] {
    const channels: PaymentChannel[] = [];
    const config = channelConfigService.getChannelConfigs();
    
    // 检查环境变量配置 AND 渠道启用状态
    if (this.isChannelConfigured(PaymentChannel.TOPPAY) && config.channels[PaymentChannel.TOPPAY]?.isEnabled) {
      channels.push(PaymentChannel.TOPPAY);
    }
    
    if (this.isChannelConfigured(PaymentChannel.PAY668) && config.channels[PaymentChannel.PAY668]?.isEnabled) {
      channels.push(PaymentChannel.PAY668);
    }
    
    if (this.isChannelConfigured(PaymentChannel.LSPPAY) && config.channels[PaymentChannel.LSPPAY]?.isEnabled) {
      channels.push(PaymentChannel.LSPPAY);
    }

    if (this.isChannelConfigured(PaymentChannel.HUIFENG) && config.channels[PaymentChannel.HUIFENG]?.isEnabled) {
      channels.push(PaymentChannel.HUIFENG);
    }

    if (this.isChannelConfigured(PaymentChannel.NASKI) && config.channels[PaymentChannel.NASKI]?.isEnabled) {
      channels.push(PaymentChannel.NASKI);
    }

    return channels;
  }

  /**
   * 根据权重和金额自动选择最优支付渠道
   * @param amount 充值金额
   * @param excludedChannels 需要排除的渠道列表（用于重试时排除已失败的渠道）
   */
  selectOptimalChannel(amount: number, excludedChannels: PaymentChannel[] = []): ChannelSelectionResult {
    const allAvailableChannels = this.getAvailableChannels();
    // 过滤掉被排除的渠道
    const availableChannels = allAvailableChannels.filter(channel => !excludedChannels.includes(channel));
    
    return channelConfigService.selectOptimalChannel(amount, availableChannels);
  }

  /**
   * 获取渠道权重配置
   */
  getChannelWeightConfig() {
    return channelConfigService.getChannelConfigs();
  }

  /**
   * 更新渠道配置
   */
  async updateChannelConfig(channel: PaymentChannel, config: any) {
    return await channelConfigService.updateChannelConfig(channel, config);
  }

  /**
   * 批量更新渠道权重
   */
  async batchUpdateWeights(weights: Record<PaymentChannel, number>) {
    return await channelConfigService.batchUpdateWeights(weights);
  }

  /**
   * 测试渠道选择算法
   */
  testChannelSelection(amount: number, testCount: number = 100) {
    const availableChannels = this.getAvailableChannels();
    return channelConfigService.testChannelSelection(amount, testCount, availableChannels);
  }

  /**
   * 生成订单号
   */
  generateOrderId(channel: PaymentChannel): string {
    switch (channel) {
      case PaymentChannel.TOPPAY:
        return this.topPayService.generateOrderId();
      case PaymentChannel.PAY668:
        return this.pay668Service.generateOrderId();
      case PaymentChannel.LSPPAY:
        return this.lspPayService.generateOrderId();
      case PaymentChannel.HUIFENG:
        return this.huifengPayService.generateOrderId();
      case PaymentChannel.NASKI:
        return this.naskiPayService.generateOrderId();
      default:
        return `ORDER${Date.now()}${Math.random().toString(36).substring(2, 6).toUpperCase()}`;
    }
  }

  /**
   * 创建提现订单
   */
  async createPayoutOrder(request: CreatePayoutOrderRequest): Promise<PaymentResponse> {
    Logger.info('开始创建提现订单', {
      orderId: request.orderId,
      channel: request.paymentChannel,
      paymentMethod: request.paymentMethod,
      amount: request.amount
    });

    // 检查支付渠道配置
    if (!this.isChannelConfigured(request.paymentChannel)) {
      throw new AppError(`支付渠道 ${request.paymentChannel} 未配置`, ErrorCode.PAYMENT_CONFIG_ERROR, {
        orderId: request.orderId,
        channel: request.paymentChannel
      });
    }

    try {
      switch (request.paymentChannel) {
        case PaymentChannel.TOPPAY:
          return await this.createTopPayPayoutOrder(request);
        case PaymentChannel.PAY668:
          return await this.createPay668PayoutOrder(request);
        case PaymentChannel.LSPPAY:
          return await this.createLspPayPayoutOrder(request);
        case PaymentChannel.HUIFENG:
          return await this.createHuifengPayoutOrder(request);
        default:
          throw new AppError(`不支持的支付渠道: ${request.paymentChannel}`, ErrorCode.PAYMENT_CHANNEL_ERROR, {
            orderId: request.orderId,
            channel: request.paymentChannel
          });
      }
    } catch (error) {
      Logger.error('创建提现订单失败', error, {
        orderId: request.orderId,
        channel: request.paymentChannel
      });
      throw error;
    }
  }

  /**
   * 创建TopPay提现订单
   */
  private async createTopPayPayoutOrder(request: CreatePayoutOrderRequest): Promise<PaymentResponse> {
    const topPayRequest: TopPayCreatePayoutOrderRequest = {
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      receiverName: request.receiverName,
      receiverBankCard: request.receiverBankCard,
      bankCode: request.bankCode,
      remark: request.remark,
    };

    const response = await this.topPayService.createPayoutOrder(topPayRequest);

    // TopPay成功的判断条件：
    // 1. platRespCode === '0000' 或
    // 2. platRespMessage包含'Success'字样
    const isSuccess = response.platRespCode === '0000' ||
                     Boolean(response.platRespMessage && response.platRespMessage.toLowerCase().includes('success'));

    return {
      success: isSuccess,
      platOrderNum: response.platOrderNum,
      payUrl: response.url,
      qrCodeUrl: response.payData,
      errorCode: response.platRespCode,
      errorMessage: response.platRespMessage,
      rawResponse: response,
    };
  }

  /**
   * 创建LSPPAY提现订单
   */
  private async createLspPayPayoutOrder(request: CreatePayoutOrderRequest): Promise<PaymentResponse> {
    const lspPayRequest: CreateLspPayPayoutRequest = {
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      receiverName: request.receiverName,
      receiverBankCard: request.receiverBankCard,
      bankCode: request.bankCode,
      customerEmail: request.customerEmail,
      customerPhone: request.customerPhone,
      remark: request.remark,
    };

    const response: LspPayPayoutResponse = await this.lspPayService.createPayoutOrder(lspPayRequest);

    // LSPPAY代付成功状态判断：code === 0 且 state === 2
    const isSuccess = response.code === 0 && response.data?.state === 2;

    return {
      success: isSuccess,
      platOrderNum: response.data?.transferId, // 使用transferId作为平台订单号
      payUrl: undefined, // 代付没有支付链接
      qrCodeUrl: undefined, // 代付没有二维码
      errorCode: response.data?.errCode || response.code?.toString(),
      errorMessage: response.data?.errMsg || response.msg,
      rawResponse: response,
    };
  }

  /**
   * 创建668Pay提现订单
   */
  private async createPay668PayoutOrder(request: CreatePayoutOrderRequest): Promise<PaymentResponse> {
    const pay668Request: CreatePay668PayoutRequest = {
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      receiverName: request.receiverName,
      receiverBankCard: request.receiverBankCard,
      bankCode: request.bankCode,
      customerEmail: request.customerEmail,
      customerPhone: request.customerPhone,
      remark: request.remark,
    };

    const response: Pay668PayoutResponse = await this.pay668Service.createPayoutOrder(pay668Request);

    // 根据668Pay代付文档，成功状态判断逻辑：
    // code === 0 表示请求成功，state字段表示转账状态
    const isSuccess = response.code === 0 && response.data?.state === 2; // state=2表示转账成功

    return {
      success: isSuccess,
      platOrderNum: response.data?.transferId, // 使用transferId作为平台订单号
      payUrl: undefined, // 代付没有支付链接
      qrCodeUrl: undefined, // 代付没有二维码
      errorCode: response.data?.errCode || response.code?.toString(),
      errorMessage: response.data?.errMsg || response.msg || (response.code !== 0 ? '代付失败' : undefined),
      rawResponse: response,
    };
  }

  /**
   * 创建NASKI充值订单
   */
  private async createNaskiOrder(request: CreatePaymentOrderRequest): Promise<PaymentResponse> {
    // 使用提供的客户信息，如果为空则使用默认值
    const customerEmail = request.customerEmail?.trim() || 'customer@naski.com';
    const customerPhone = request.customerPhone?.trim() || '0000000000';

    const naskiRequest: CreateNaskiOrderRequest = {
      userId: request.userId,
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      transAccNo: request.transAccNo,
      paymentName: request.paymentName,
      bankCode: request.bankCode,
      customerEmail,
      customerPhone,
      extendParam: request.extendParam?.trim() || undefined,
    };

    const response: NaskiOrderResponse = await this.naskiPayService.createRechargeOrder(naskiRequest);

    // NASKI成功状态判断：code === 200 且 data.status === 2(待支付)
    const isSuccess = response.code === 200 && response.data?.status === 2;

    return {
      success: isSuccess,
      platOrderNum: response.data?.orderNo,
      payUrl: response.data?.orderData || undefined,  // orderData包含支付链接或二维码
      qrCodeUrl: undefined, // 如果需要区分,可以根据orderData类型判断
      errorCode: response.data?.subCode || response.code?.toString(),
      errorMessage: response.data?.subMsg || response.msg,
      rawResponse: response,
    };
  }

  /**
   * 创建汇沣支付提现订单
   */
  private async createHuifengPayoutOrder(request: CreatePayoutOrderRequest): Promise<PaymentResponse> {
    const huifengRequest: CreateHuifengPayoutRequest = {
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      receiverName: request.receiverName,
      receiverBankCard: request.receiverBankCard,
      bankCode: request.bankCode,
      accountName: request.accountName ?? request.receiverName,
      bankName: request.bankName,
      certificate: request.certificate,
      subbranch: request.subbranch,
      customerEmail: request.customerEmail,
      customerPhone: request.customerPhone,
      userIp: request.userIp,
      extra: request.extra,
      remark: request.remark,
    };

    const response: HuifengPayoutResponse = await this.huifengPayService.createPayoutOrder(huifengRequest);

    // 汇沣支付成功状态判断：code === 0
    const isSuccess = response.code === 0;

    return {
      success: isSuccess,
      platOrderNum: response.data?.order_num,
      payUrl: undefined, // 代付没有支付链接
      qrCodeUrl: undefined, // 代付没有二维码
      errorCode: response.code?.toString(),
      errorMessage: response.message,
      rawResponse: response,
    };
  }

  /**
   * 创建充值订单
   */
  async createRechargeOrder(request: CreatePaymentOrderRequest): Promise<PaymentResponse> {
    Logger.info('开始创建支付订单', {
      orderId: request.orderId,
      channel: request.paymentChannel,
      paymentMethod: request.paymentMethod,
      amount: request.amount
    });

    // 检查支付渠道配置
    if (!this.isChannelConfigured(request.paymentChannel)) {
      throw new AppError(`支付渠道 ${request.paymentChannel} 未配置`, ErrorCode.PAYMENT_CONFIG_ERROR, {
        orderId: request.orderId,
        channel: request.paymentChannel
      });
    }

    try {
      switch (request.paymentChannel) {
        case PaymentChannel.TOPPAY:
          return await this.createTopPayOrder(request);
        case PaymentChannel.PAY668:
          return await this.createPay668Order(request);
        case PaymentChannel.LSPPAY:
          return await this.createLspPayOrder(request);
        case PaymentChannel.HUIFENG:
          return await this.createHuifengOrder(request);
        case PaymentChannel.NASKI:
          return await this.createNaskiOrder(request);
        default:
          throw new AppError(`不支持的支付渠道: ${request.paymentChannel}`, ErrorCode.PAYMENT_CHANNEL_ERROR, {
            orderId: request.orderId,
            channel: request.paymentChannel
          });
      }
    } catch (error) {
      Logger.error('创建支付订单失败', error, {
        orderId: request.orderId,
        channel: request.paymentChannel
      });
      throw error;
    }
  }

  /**
   * 创建TopPay订单
   */
  private async createTopPayOrder(request: CreatePaymentOrderRequest): Promise<PaymentResponse> {
    const topPayRequest: TopPayCreateOrderRequest = {
      userId: request.userId,
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      transAccNo: request.transAccNo,
      paymentName: request.paymentName,
      bankCode: request.bankCode,
      extendParam: request.extendParam,
    };

    const response = await this.topPayService.createRechargeOrder(topPayRequest);

    // TopPay成功的判断条件：
    // 1. platRespCode === '0000' 或
    // 2. platRespMessage包含'Success'字样
    const isSuccess = response.platRespCode === '0000' ||
                     Boolean(response.platRespMessage && response.platRespMessage.toLowerCase().includes('success'));

    return {
      success: isSuccess,
      platOrderNum: response.platOrderNum,
      payUrl: response.url,
      qrCodeUrl: response.payData,
      errorCode: response.platRespCode,
      errorMessage: response.platRespMessage,
      rawResponse: response,
    };
  }

  /**
   * 创建LSPPAY订单
   */
  private async createLspPayOrder(request: CreatePaymentOrderRequest): Promise<PaymentResponse> {
    const lspPayRequest: CreateLspPayOrderRequest = {
      userId: request.userId,
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      transAccNo: request.transAccNo,
      paymentName: request.paymentName,
      bankCode: request.bankCode,
      customerEmail: request.customerEmail,
      customerPhone: request.customerPhone,
      extendParam: request.extendParam,
    };

    const response: LspPayOrderResponse = await this.lspPayService.createRechargeOrder(lspPayRequest);

    // LSPPAY成功状态判断：code === 0
    const isSuccess = response.code === 0;

    return {
      success: isSuccess,
      platOrderNum: response.data?.payOrderId,
      payUrl: (response.data?.payDataType === 'payUrl' || response.data?.payDataType === 'payurl') ? response.data.payData : undefined,
      qrCodeUrl: response.data?.payDataType === 'codeUrl' || response.data?.payDataType === 'codeImgUrl' ? response.data.payData : undefined,
      errorCode: response.data?.errCode || response.code?.toString(),
      errorMessage: response.data?.errMsg || response.msg,
      rawResponse: response,
    };
  }

  /**
   * 创建668Pay订单
   */
  private async createPay668Order(request: CreatePaymentOrderRequest): Promise<PaymentResponse> {
    const pay668Request: CreatePay668OrderRequest = {
      userId: request.userId,
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      transAccNo: request.transAccNo,
      paymentName: request.paymentName,
      bankCode: request.bankCode,
      customerEmail: request.customerEmail,
      customerPhone: request.customerPhone,
      extendParam: request.extendParam,
    };

    const response = await this.pay668Service.createRechargeOrder(pay668Request);

    return {
      success: response.code === 0,
      platOrderNum: response.data?.payOrderId,
      payUrl: response.data?.payDataType === 'payUrl' ? response.data.payData : undefined,
      qrCodeUrl: response.data?.payDataType === 'codeUrl' || response.data?.payDataType === 'codeImgUrl' ? response.data.payData : undefined,
      errorCode: response.data?.errCode || response.code?.toString(),
      errorMessage: response.data?.errMsg || response.msg,
      rawResponse: response,
    };
  }

  /**
   * 创建汇沣支付订单
   */
  private async createHuifengOrder(request: CreatePaymentOrderRequest): Promise<PaymentResponse> {
    // 使用提供的客户信息，如果为空则使用默认值
    const customerEmail = request.customerEmail?.trim() || 'customer@taiguo-recharge.com';
    const customerPhone = request.customerPhone?.trim() || '+66123456789';

    const huifengRequest: CreateHuifengOrderRequest = {
      userId: request.userId,
      amount: request.amount,
      paymentMethod: request.paymentMethod,
      orderId: request.orderId,
      transAccNo: request.transAccNo,
      paymentName: request.paymentName,
      bankCode: request.bankCode,
      customerEmail,
      customerPhone,
      extendParam: request.extendParam?.trim() || undefined,
    };

    const response: HuifengOrderResponse = await this.huifengPayService.createRechargeOrder(huifengRequest);

    // 汇沣支付成功状态判断：code === 0
    const isSuccess = response.code === 0;

    return {
      success: isSuccess,
      platOrderNum: response.data?.order_num,
      payUrl: response.data?.type === 1 ? response.data.pay_url : undefined,
      qrCodeUrl: response.data?.type === 2 ? response.data.qr_code : undefined,
      errorCode: response.code?.toString(),
      errorMessage: response.message,
      rawResponse: response,
    };
  }

  /**
   * 验证异步通知
   */
  verifyNotification(channel: PaymentChannel, data: any): boolean {
    try {
      switch (channel) {
        case PaymentChannel.TOPPAY:
          return this.topPayService.verifyNotification(data);
        case PaymentChannel.PAY668:
          return this.pay668Service.verifyNotification(data);
        case PaymentChannel.LSPPAY:
          return this.lspPayService.verifyNotification(data);
        case PaymentChannel.HUIFENG:
          return this.huifengPayService.verifyNotification(data);
        case PaymentChannel.NASKI:
          return this.naskiPayService.verifyNotification(data);
        default:
          Logger.error('不支持的支付渠道通知验证', new Error(`Unsupported channel: ${channel}`), { channel });
          return false;
      }
    } catch (error) {
      Logger.error('支付通知验证失败', error, { channel });
      return false;
    }
  }

  /**
   * 解析异步通知数据
   */
  parseNotification(channel: PaymentChannel, data: any): PaymentNotification | null {
    try {
      switch (channel) {
        case PaymentChannel.TOPPAY:
          return {
            channel: PaymentChannel.TOPPAY,
            orderId: data.orderNum,
            platOrderNum: data.platOrderNum,
            status: data.status,
            amount: data.payMoney,
            payFee: data.payFee,
            rawData: data,
          };
        case PaymentChannel.PAY668:
          return {
            channel: PaymentChannel.PAY668,
            orderId: data.mchOrderNo,
            platOrderNum: data.payOrderId,
            status: this.mapPay668Status(data.orderState),
            amount: data.amount,
            payFee: undefined, // 668Pay 没有手续费字段
            rawData: data,
          };
        case PaymentChannel.LSPPAY:
          return {
            channel: PaymentChannel.LSPPAY,
            orderId: data.mchOrderNo,
            platOrderNum: data.payOrderId || data.transferId, // 代付用transferId，充值用payOrderId
            status: this.mapLspPayStatus(data.state || data.orderState), // 代付用state，充值用orderState
            amount: data.amount,
            payFee: undefined, // LSPPAY 没有手续费字段
            rawData: data,
          };
        case PaymentChannel.HUIFENG:
          return {
            channel: PaymentChannel.HUIFENG,
            orderId: data.orderId || data.merchantOrderId,
            platOrderNum: data.orderNum,
            status: this.mapHuifengStatus(data.status),
            amount: data.amount,
            payFee: undefined, // 汇沣支付没有手续费字段
            rawData: data,
          };
        case PaymentChannel.NASKI:
          return {
            channel: PaymentChannel.NASKI,
            orderId: data.merOrderNo,
            platOrderNum: data.orderNo,
            status: this.mapNaskiStatus(data.status),
            amount: data.payAmount || data.orderAmount, // 使用实际支付金额，fallback到订单金额
            payFee: undefined, // NASKI 没有手续费字段
            rawData: data,
          };
        default:
          Logger.error('不支持的支付渠道通知解析', new Error(`Unsupported channel: ${channel}`), { channel });
          return null;
      }
    } catch (error) {
      Logger.error('支付通知解析失败', error, { channel });
      return null;
    }
  }

  /**
   * 映射668Pay状态到统一状态
   */
  private mapPay668Status(orderState: number): string {
    switch (orderState) {
      case 0: return 'INIT_ORDER';
      case 1: return 'NO_PAY';
      case 2: return 'SUCCESS';
      case 3: return 'PAY_ERROR';
      case 4: return 'PAY_CANCEL';
      case 5: return 'REFUND';
      case 6: return 'CLOSED';
      case 7: return 'PENDING_SETTLEMENT';
      default: return 'UNKNOWN';
    }
  }

  /**
   * 映射LSPPAY状态到统一状态
   */
  private mapLspPayStatus(state: number): string {
    switch (state) {
      case 0: return 'INIT_ORDER';
      case 1: return 'NO_PAY';
      case 2: return 'SUCCESS';
      case 3: return 'PAY_ERROR';
      case 4: return 'PAY_CANCEL';
      case 5: return 'REFUND';
      case 6: return 'CLOSED';
      default: return 'UNKNOWN';
    }
  }

  /**
   * 映射汇沣支付状态到统一状态
   */
  private mapHuifengStatus(status: number): string {
    switch (status) {
      case 200: return 'SUCCESS';
      case 999: return 'PAY_ERROR';
      case 666: return 'PAY_CANCEL'; // 超时当作取消
      default: return 'UNKNOWN';
    }
  }

  /**
   * 映射NASKI状态到统一状态
   * status=5表示支付成功，status=4表示订单已关闭，status=2表示待支付，status=3表示失败
   */
  private mapNaskiStatus(status: number): string {
    switch (status) {
      case 5: return 'SUCCESS';      // 成功
      case 4: return 'PAY_CANCEL';   // 关闭
      case 2: return 'NO_PAY';       // 待支付
      case 3: return 'PAY_ERROR';    // 失败
      default: return 'UNKNOWN';
    }
  }

  /**
   * 获取支付渠道显示名称
   */
  getChannelDisplayName(channel: PaymentChannel): string {
    switch (channel) {
      case PaymentChannel.TOPPAY:
        return 'TopPay';
      case PaymentChannel.PAY668:
        return '668Pay';
      case PaymentChannel.LSPPAY:
        return 'LSPPAY';
      case PaymentChannel.HUIFENG:
        return '汇沣支付';
      case PaymentChannel.NASKI:
        return 'NASKI';
      default:
        return channel;
    }
  }
}

// 创建支付服务实例
export const paymentService = new PaymentService();
